/*
 * node.c
 *
 *  Created on: Mar 17, 2024
 *      Author: 25119
 */

#include "node.h"
#include "tim.h"

////////////////////---------A72 Gateway function---------////////////////////
// 重启模块
inline int A72N_reboot(void)
{
  return A72_tx_cmd(&NODE_UART_HANDLE, C_A72_T_reboot);
}

// 模块恢复出场设置
inline int A72N_restore(void)
{
  return A72_tx_cmd(&NODE_UART_HANDLE, C_A72_T_restore);
}

// 获取MAC地址和通信地址
int A72N_get_mac_addr(Node_info *node)
{
  uint8_t temp[0xA0];
  A72_tx_cmd(&NODE_UART_HANDLE, C_A72_T_read_address);
  A72_rx_cmd(&NODE_UART_HANDLE, temp);
  if (A72_cmd_cmp(temp, C_A72_R_read_address) == 0)
  {
    memcpy(node->mac, temp + 2, 8);
  }
  else
  {
    return -1;
  }

  return 0;
}

int A72N_rx_uart_it_cb(UART_HandleTypeDef *huart, bool reset)
{
  static bool head = true;
  static uint8_t flag = 0;

  if (reset)
  {
    HAL_UART_AbortReceive(huart);
    HAL_TIM_Base_Stop_IT(&htim16);
    head = true;
    flag = 0;
  }

  if (head)
  {
    if (flag == 2)
    {
      rx_buf.done = 1;
    }
    flag = 1;
    HAL_UART_Receive_IT(huart, (uint8_t*)&rx_buf.len, 2);
    head = false;
  }
  else
  {
    HAL_UART_Receive_IT(huart, rx_buf.data, rx_buf.len);
    head = true;
    flag = 2;

    TIM16->CNT = 0;
    __HAL_TIM_CLEAR_FLAG(&htim16, TIM_FLAG_UPDATE);
    HAL_TIM_Base_Start_IT(&htim16);
  }

  return 0;
}
